//
// Created by tcj on 2022/7/13.
//

#include "epoll.h"

namespace tcj{
    epoller::epoller(int maxEvent):epollFd_(epoll_create(512)),events_(maxEvent){
        assert(epollFd_>=0 && events_.size()>0);
    }

    epoller::~epoller() {
        close(epollFd_);
    }

    bool epoller::addFd(int fd, uint32_t events) {
        if(fd<0) return false;
        epoll_event ev = {0};
        ev.data.fd =fd;
        ev.events = events;
        return 0 == epoll_ctl(epollFd_,EPOLL_CTL_ADD,fd,&ev);
    }

    bool epoller::modFd(int fd, uint32_t events) {
        if(fd<0) return false;
        epoll_event ev = {0};
        ev.data.fd =fd;
        ev.events = events;
        return 0 == epoll_ctl(epollFd_,EPOLL_CTL_MOD,fd,&ev);
    }

    bool epoller::delFd(int fd) {
        if(fd<0) return false;
        epoll_event ev = {0};
        return 0 == epoll_ctl(epollFd_,EPOLL_CTL_DEL,fd,&ev);
    }

    int epoller::wait(int timewait) {
        return epoll_wait(epollFd_,&events_[0],static_cast<int>(events_.size()),timewait);
    }

    int epoller::getEventFd(size_t i) const {
        assert(i < events_.size() && i>=0);
        return events_[i].data.fd;
    }

    uint32_t epoller::getEvents(size_t i) const {
        assert(i<events_.size() && i>=0);
        return events_[i].events;
    }
}